<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div class="search" v-show="showSearch">
        <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px" class="search-form">
          <el-form-item label="学生姓名" prop="realName">
            <el-input v-model="queryParams.realName" placeholder="请输入学生姓名" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="学号" prop="studentNo">
            <el-input v-model="queryParams.studentNo" placeholder="请输入学号" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="家长姓名" prop="parentName">
            <el-input v-model="queryParams.parentName" placeholder="请输入家长姓名" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="家长电话" prop="parentPhone">
            <el-input v-model="queryParams.parentPhone" placeholder="请输入家长电话" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="学生状态" prop="status">
            <el-select v-model="queryParams.status" placeholder="请选择学生状态" clearable>
              <el-option v-for="dict in student_school_status" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="所属班级" prop="belongId">
            <el-tree-select
              v-model="queryParams.belongId"
              :data="classOptions"
              :props="{ value: 'id', label: 'label', children: 'children' }"
              value-key="classId"
              placeholder="请选择班级"
              check-strictly
              default-expand-all
            />
          </el-form-item>
          <el-form-item label="级别" prop="gradeLevel">
            <el-select v-model="queryParams.gradeLevel" placeholder="请选择级别" clearable>
              <el-option v-for="dict in school_grade_level" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="所属学部" prop="facultyId">
            <el-select v-model="queryParams.facultyId" placeholder="请选择所属学部" clearable>
              <el-option v-for="dict in faculty_type" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="住宿类型" prop="accommodationType">
            <el-select v-model="queryParams.accommodationType" placeholder="请选择住宿类型" clearable>
              <el-option v-for="dict in student_accommodation_type" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
          <!--          <el-form-item label="人脸状态">-->
          <!--            <el-select v-model="queryParams.facePicStatus" placeholder="请选择">-->
          <!--              <el-option v-for="dict in face_pic_status" :key="dict.value" :label="dict.label" :value="parseInt(dict.value)"></el-option>-->
          <!--            </el-select>-->
          <!--          </el-form-item>-->
          <!--          <el-form-item label="一卡通" prop="eCardNo">-->
          <!--            <el-input v-model="queryParams.eCardNo" placeholder="请输入一卡通" clearable style="width: 240px" @keyup.enter="handleQuery" />-->
          <!--          </el-form-item>-->
          <el-form-item label="订阅状态" prop="subscribeStatus">
            <el-select v-model="queryParams.subscribeStatus" placeholder="请选择订阅状态" clearable>
              <el-option v-for="dict in student_subscribe_status" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="Plus" @click="handleAdd" v-hasPermi="['office:student:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['office:student:edit']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['office:student:remove']">删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button icon="Download" @click="handleExport" v-hasPermi="['office:student:export']">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table
        height="calc(100vh - 470px)"
        stripe
        v-loading="loading"
        :data="studentList"
        @selection-change="handleSelectionChange"
        @row-dblclick="(row: any, column: any, event: Event) => handleUpdate(row)"
      >
        <el-table-column type="selection" width="55" align="center" />
        <!--        <el-table-column label="" align="center" prop="id" v-if="true" />-->
        <el-table-column label="照片" align="center" prop="facePic" width="100">
          <template #default="scope">
            <image-preview :src="scope.row.facePic || scope.row.facePicExtra" :width="50" :height="50" />
          </template>
        </el-table-column>
        <el-table-column label="姓名" align="center" prop="realName" />
        <el-table-column label="性别" align="center" prop="gender">
          <template #default="scope">
            <dict-tag :options="student_sex" :value="scope.row.gender" />
          </template>
        </el-table-column>
        <el-table-column label="所属班级" align="center" prop="className" />
        <el-table-column label="学部" align="center" prop="facultyId">
          <template #default="scope">
            <dict-tag :options="faculty_type" :value="parseInt(scope.row.facultyId)" />
          </template>
        </el-table-column>
        <!--        <el-table-column label="一卡通编号" align="center" prop="eCardNo" />-->
        <el-table-column label="学号" align="center" prop="studentNo" />
        <el-table-column label="学生状态" align="center" prop="status">
          <template #default="scope">
            <dict-tag :options="student_school_status" :value="scope.row.status" />
          </template>
        </el-table-column>
        <el-table-column label="住宿类型" align="center" prop="accommodationType">
          <template #default="scope">
            <dict-tag :options="student_accommodation_type" :value="scope.row.accommodationType" />
          </template>
        </el-table-column>
        <el-table-column label="关联监护人" align="center" prop="guardians" />
        <el-table-column label="订阅状态" align="center" prop="subscribeStatus">
          <template #default="scope">
            <dict-tag :options="student_subscribe_status" :value="scope.row.subscribeStatus" />
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['office:student:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['office:student:remove']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total>0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改学生信息对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="900px" append-to-body>
      <el-form ref="studentFormRef" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="5">
            照片
            <div style="text-align: center; padding-bottom: 10px">
              <image-upload v-model="form.facePic" :isShowTip="false" list-type="text" :limit="1" :verifyWay="1" />
              <el-tag type="primary">教职工上传</el-tag>
            </div>
            <div style="text-align: center">
              <image-preview :src="form.facePicExtra" :width="148" :height="148" />
<!--              <image-upload v-model="form.facePicExtra" :isShowTip="false" list-type="text" :limit="1" :verifyWay="1" disabled/>-->
              <el-tag type="primary">家长上传</el-tag>
            </div>
          </el-col>
          <el-col :span="18">
            <el-row>
              <el-col :span="8">
                <el-form-item label="所在班级" prop="classId">
                  <el-tree-select
                    v-model="form.classId"
                    :data="classOptions"
                    :props="{ value: 'id', label: 'label', children: 'children' }"
                    value-key="classId"
                    placeholder="请选择班级"
                    check-strictly
                    default-expand-all
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="姓名" prop="realName">
                  <el-input v-model="form.realName" placeholder="请输入姓名" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="性别" prop="gender">
                  <el-select v-model="form.gender" placeholder="请选择">
                    <el-option v-for="dict in student_sex" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="8">
                <el-form-item label="学号" prop="studentNo">
                  <el-input v-model="form.studentNo" placeholder="请输入学号" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="在校状态" prop="status">
                  <el-select v-model="form.status" placeholder="请选择">
                    <el-option v-for="dict in student_school_status" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="住宿类型" prop="accommodationType">
                  <el-select v-model="form.accommodationType" placeholder="请选择">
                    <el-option v-for="dict in student_accommodation_type" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="14">
                <el-form-item label="身份证号" prop="idCardNo">
                  <el-input v-model="form.idCardNo" placeholder="请输入身份证号" @change="setBirthdayByIdCard" />
                </el-form-item>
              </el-col>
              <el-col :span="10">
                <el-form-item label="出生日期" prop="birthday">
                  <el-date-picker
                    clearable
                    v-model="form.birthday"
                    type="date"
                    value-format="YYYYMMDD"
                    format="YYYY-MM-DD"
                    placeholder="出生日期"
                    :disabled-date="(date) => date.getTime() > Date.now()"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <!--              <el-col :span="12">-->
              <!--                <el-form-item label="一卡通号" prop="eCardNo">-->
              <!--                  <el-input v-model="form.eCardNo" placeholder="请输入一卡通号" />-->
              <!--                </el-form-item>-->
              <!--              </el-col>-->
              <el-col :span="14">
                <el-form-item label="户籍" prop="censusRegister">
                  <el-input v-model="form.censusRegister" placeholder="请输入户籍" />
                </el-form-item>
              </el-col>
              <el-col :span="10">
                <el-form-item label="关联宿舍">
                  <DormitoryTree ref="dormitoryTree" v-model="form.dormId" @node-click="handleNodeClick" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item label="住址" prop="address">
                  <el-input v-model="form.address" placeholder="请输入住址" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
            </el-form-item>
            <el-row v-for="(item, index) in form.guardianList">
              <el-col :span="7">
                <el-form-item
                  label="关系"
                  :prop="'guardianList.' + index + '.relationType'"
                  :rules="{ required: true, message: '联系人关系不能为空', trigger: 'change' }"
                >
                  <el-select v-model="item.relationType" placeholder="请选择" style="width: 120px">
                    <el-option v-for="dict in student_guardian_relation" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="7">
                <el-form-item
                  label="姓名"
                  :prop="'guardianList.' + index + '.realName'"
                  :rules="{ required: true, message: '联系人姓名不能为空', trigger: 'blur' }"
                >
                  <el-input v-model="item.realName" placeholder="请输入姓名" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item
                  label="联系电话"
                  :prop="'guardianList.' + index + '.phone'"
                  :rules="[
                  { required: true, message: '联系人电话不能为空', trigger: 'blur' },
                  { validator: phoneValidator, trigger: 'blur', }
                ]"
                >
                  <el-input v-model="item.phone" placeholder="请输入联系电话" />
                </el-form-item>
              </el-col>
              <el-col :span="2">
                <el-button type="danger" plain icon="Delete" @click="removeGuardian(item)"></el-button>
              </el-col>
            </el-row>
            <el-form-item>
              <el-button plain icon="Plus" @click="addGuardian">添加监护人</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Student" lang="ts">
import { pageStudent, getStudent, delStudent, addStudent, updateStudent } from '@/api/office/student';
import { StudentVO, StudentQuery, StudentForm } from '@/api/office/student/types';
import { listClassInfo, classTree } from '@/api/office/class';
import { listGradeInfo } from '@/api/office/grade';
import { uuid } from '@/utils/ruoyi';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const {
  student_accommodation_type,
  student_sex,
  student_subscribe_status,
  student_school_status,
  faculty_type,
  face_pic_status,
  student_guardian_relation,
  school_grade_level
} = toRefs<any>(
  proxy?.useDict(
    'student_accommodation_type',
    'student_sex',
    'student_subscribe_status',
    'student_school_status',
    'faculty_type',
    'face_pic_status',
    'student_guardian_relation',
    'school_grade_level'
  )
);

const studentList = ref<StudentVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const classOptions = ref<any[]>([]);
const gradeOptions = ref<any[]>([]);
const queryFormRef = ref<ElFormInstance>();
const studentFormRef = ref<ElFormInstance>();
const idCardNoValidator = (rule, value, callback) => {
  const reg =
    /^(^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$)|(^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])((\d{4})|\d{3}[Xx])$)$/;
  if (!reg.test(value)) {
    callback(new Error('请输入正确的身份证号'));
  } else {
    callback();
  }
};
const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: StudentForm = {
  id: undefined,
  account: undefined,
  realName: undefined,
  facePic: undefined,
  facePicStatus: undefined,
  gender: undefined,
  classId: undefined,
  facultyId: undefined,
  dormId: undefined,
  eCardNo: undefined,
  studentNo: undefined,
  status: undefined,
  accommodationType: undefined,
  subscribeStatus: undefined,
  guardianList: []
};
const data = reactive<PageData<StudentForm, StudentQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    account: undefined,
    realName: undefined,
    facePicStatus: undefined,
    gender: undefined,
    classId: undefined,
    facultyId: undefined,
    dormId: undefined,
    eCardNo: undefined,
    studentNo: undefined,
    status: undefined,
    accommodationType: undefined,
    subscribeStatus: undefined,
    params: {}
  },
  rules: {
    account: [{ required: true, message: '平台账号不能为空', trigger: 'blur' }],
    realName: [{ required: true, message: '学生姓名不能为空', trigger: 'blur' }],
    gender: [{ required: true, message: '性别不能为空', trigger: 'change' }],
    classId: [{ required: true, message: '班级不能为空', trigger: 'change' }],
    facultyId: [{ required: true, message: '学部不能为空', trigger: 'change' }],
    dormId: [{ required: true, message: '关联宿舍不能为空', trigger: 'change' }],
    idCardNo: [
      { required: true, message: '身份证号不能为空', trigger: 'blur' },
      { validator: idCardNoValidator, trigger: 'blur' }
    ],
    studentNo: [{ required: true, message: '学号不能为空', trigger: 'blur' }],
    status: [{ required: true, message: '学生状态不能为空', trigger: 'change' }],
    accommodationType: [{ required: true, message: '住宿类型不能为空', trigger: 'change' }],
    subscribeStatus: [{ required: true, message: '订阅状态不能为空', trigger: 'change' }]
  }
});

const phoneValidator = (rule, value, callback) => {
  const reg = /^1[3-9]\d{9}$/;
  if (!value) {
    callback(new Error('联系人电话不能为空'));
  } else if (!reg.test(value)) {
    callback(new Error('请输入正确的手机号'));
  } else {
    callback();
  }
};

const { queryParams, form, rules } = toRefs(data);

const dormitoryTree = ref();

const handleNodeClick = (data: any) => {
  form.value.dormId = data.sourceId;
};

/** 查询学生信息列表 */
const getList = async () => {
  loading.value = true;
  const res = await pageStudent(queryParams.value);
  studentList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  dormitoryTree.value?.clear();
  form.value.guardianList = [];
  studentFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: StudentVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

const addGuardian = () => {
  form.value.guardianList.push({ idx: uuid() });
};

const removeGuardian = (item: any) => {
  form.value.guardianList = form.value.guardianList.filter((e) => e.idx !== item.idx);
};

const setBirthdayByIdCard = () => {
  // 身份证上出生日期的位置为6至14
  form.value.birthday = form.value.idCardNo?.substring(6, 14);
};

const getClassTree = async () => {
  const res = await classTree();
  classOptions.value = res.data;
};

const getGradeList = async () => {
  const res = await listGradeInfo();
  gradeOptions.value = res.rows;
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  addGuardian();
  dialog.visible = true;
  dialog.title = '添加学生信息';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: StudentVO) => {
  reset();
  const _id = row?.id || ids.value[0];
  const res = await getStudent(_id);
  Object.assign(form.value, res.data);
  if (!form.value.birthday) {
    setBirthdayByIdCard();
  }
  dialog.visible = true;
  dialog.title = '修改学生信息';
};

/** 提交按钮 */
const submitForm = () => {
  studentFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateStudent(form.value).finally(() => (buttonLoading.value = false));
        proxy?.$modal.msgSuccess('修改成功');
      } else {
        await addStudent(form.value).finally(() => (buttonLoading.value = false));
        proxy?.$modal.msgSuccess('新增成功');
      }
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: StudentVO) => {
  const _ids = row ? [row.id] : ids.value;
  let msg = studentList.value
    .filter((e) => _ids.find((id) => e.id === id))
    .map((e) => e.realName)
    .join(',');
  await proxy?.$modal.confirm('是否确认删除学生姓名为"' + msg + '"的数据项？').finally(() => (loading.value = false));
  await delStudent(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'office/student/export',
    {
      ...queryParams.value
    },
    `student_${new Date().getTime()}.xlsx`
  );
};

onMounted(() => {
  getGradeList();
  getClassTree();
  getList();
});
</script>
